<template>
  <div class="user-profile-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">个人资料</h1>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 个人资料内容 -->
    <div v-else class="profile-content">
      <!-- 左侧个人信息卡片 -->
      <div class="profile-sidebar">
        <el-card class="profile-card">
          <!-- 用户头像 -->
          <div class="avatar-section">
            <el-avatar :size="120" class="user-avatar">
              <img v-if="userProfile.avatarUrl" :src="userProfile.avatarUrl" alt="用户头像" />
              <span v-else>{{ userProfile.nickname.charAt(0).toUpperCase() }}</span>
            </el-avatar>
            <div class="avatar-upload">
              <el-button type="primary" size="small" @click="handleAvatarUpload">更换头像</el-button>
            </div>
          </div>

          <!-- 用户基本信息 -->
          <div class="user-info">
            <h3 class="user-name">{{ userProfile.nickname }}</h3>
            <p class="user-id">ID: {{ userProfile.id }}</p>
            <p class="user-level">等级: {{ userProfile.level }}级</p>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-number">{{ userProfile.totalScore }}</span>
                <span class="stat-label">积分</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ userProfile.solvedQuestions }}</span>
                <span class="stat-label">已解题</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ userProfile.joinGroups }}</span>
                <span class="stat-label">加入小组</span>
              </div>
            </div>
          </div>

          <!-- 个人标签 -->
          <div class="user-tags">
            <el-tag v-for="tag in userProfile.tags" :key="tag" size="small" type="info">
              {{ tag }}
            </el-tag>
          </div>

          <!-- 用户简介 -->
          <div class="user-bio" v-if="userProfile.bio">
            <h4 class="section-title">个人简介</h4>
            <p>{{ userProfile.bio }}</p>
          </div>

          <!-- 联系方式 -->
          <div class="user-contact">
            <h4 class="section-title">联系方式</h4>
            <div class="contact-item">
              <el-icon class="contact-icon"><Phone /></el-icon>
              <span>{{ userProfile.phone || '未设置' }}</span>
            </div>
            <div class="contact-item">
              <el-icon class="contact-icon"><Message /></el-icon>
              <span>{{ userProfile.email || '未设置' }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧详细信息和设置 -->
      <div class="profile-main">
        <!-- 基本信息编辑 -->
        <el-card class="info-edit-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button 
                v-if="!isEditing" 
                type="primary" 
                size="small" 
                @click="isEditing = true"
              >
                编辑
              </el-button>
              <div v-if="isEditing" class="edit-actions">
                <el-button type="primary" size="small" @click="saveChanges">保存</el-button>
                <el-button type="default" size="small" @click="cancelEdit">取消</el-button>
              </div>
            </div>
          </template>

          <el-form
            ref="profileFormRef"
            v-model="editForm"
            :rules="profileRules"
            class="profile-form"
            label-width="100px"
          >
            <el-form-item label="昵称">
              <el-input
                v-if="isEditing"
                v-model="editForm.nickname"
                placeholder="请输入昵称"
                :validate-event="false"
              />
              <span v-else class="form-value">{{ userProfile.nickname }}</span>
            </el-form-item>

            <el-form-item label="性别">
              <div v-if="isEditing">
                <el-radio-group v-model="editForm.gender">
                  <el-radio :label="'male'">男</el-radio>
                  <el-radio :label="'female'">女</el-radio>
                  <el-radio :label="'other'">其他</el-radio>
                </el-radio-group>
              </div>
              <span v-else class="form-value">{{ genderMap[userProfile.gender] || '未设置' }}</span>
            </el-form-item>

            <el-form-item label="生日">
              <div v-if="isEditing">
                <el-date-picker
                  v-model="editForm.birthday"
                  type="date"
                  placeholder="选择生日"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
                />
              </div>
              <span v-else class="form-value">{{ userProfile.birthday || '未设置' }}</span>
            </el-form-item>

            <el-form-item label="地区">
              <div v-if="isEditing">
                <el-cascader
                  v-model="editForm.location"
                  :options="locationOptions"
                  placeholder="选择省/市/区"
                  style="width: 100%;"
                />
              </div>
              <span v-else class="form-value">{{ userProfile.location || '未设置' }}</span>
            </el-form-item>

            <el-form-item label="个性签名">
              <div v-if="isEditing">
                <el-input
                  v-model="editForm.bio"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入个性签名"
                  :validate-event="false"
                />
              </div>
              <span v-else class="form-value">{{ userProfile.bio || '未设置' }}</span>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <div v-if="isEditing">
                <el-input
                  v-model="editForm.phone"
                  placeholder="请输入手机号"
                  :validate-event="false"
                />
              </div>
              <span v-else class="form-value">{{ userProfile.phone || '未设置' }}</span>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <div v-if="isEditing">
                <el-input
                  v-model="editForm.email"
                  placeholder="请输入邮箱"
                  :validate-event="false"
                />
              </div>
              <span v-else class="form-value">{{ userProfile.email || '未设置' }}</span>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 学习数据统计 -->
        <el-card class="study-stats-card">
          <template #header>
            <div class="card-header">
              <span>学习数据</span>
            </div>
          </template>

          <div class="stats-charts">
            <!-- 学习时长统计 -->
            <div class="chart-item">
              <h4 class="chart-title">学习时长统计</h4>
              <div class="chart-container">
                <!-- 这里应该是图表组件，暂时用静态数据展示 -->
                <div class="static-chart">
                  <div class="chart-bar">
                    <div class="bar" style="width: 80%; background-color: #6366f1;"></div>
                    <span>周一</span>
                  </div>
                  <div class="chart-bar">
                    <div class="bar" style="width: 60%; background-color: #8b5cf6;"></div>
                    <span>周二</span>
                  </div>
                  <div class="chart-bar">
                    <div class="bar" style="width: 90%; background-color: #ec4899;"></div>
                    <span>周三</span>
                  </div>
                  <div class="chart-bar">
                    <div class="bar" style="width: 70%; background-color: #f43f5e;"></div>
                    <span>周四</span>
                  </div>
                  <div class="chart-bar">
                    <div class="bar" style="width: 95%; background-color: #f97316;"></div>
                    <span>周五</span>
                  </div>
                  <div class="chart-bar">
                    <div class="bar" style="width: 65%; background-color: #eab308;"></div>
                    <span>周六</span>
                  </div>
                  <div class="chart-bar">
                    <div class="bar" style="width: 50%; background-color: #22c55e;"></div>
                    <span>周日</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 学习进度 -->
            <div class="learning-progress">
              <h4 class="chart-title">学习进度</h4>
              <div class="progress-items">
                <div class="progress-item">
                  <div class="progress-info">
                    <span class="progress-name">行测题库</span>
                    <span class="progress-percentage">65%</span>
                  </div>
                  <el-progress :percentage="65" />
                </div>
                <div class="progress-item">
                  <div class="progress-info">
                    <span class="progress-name">申论题库</span>
                    <span class="progress-percentage">42%</span>
                  </div>
                  <el-progress :percentage="42" />
                </div>
                <div class="progress-item">
                  <div class="progress-info">
                    <span class="progress-name">时政热点</span>
                    <span class="progress-percentage">88%</span>
                  </div>
                  <el-progress :percentage="88" />
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 学习偏好设置 -->
        <el-card class="learning-prefs-card">
          <template #header>
            <div class="card-header">
              <span>学习偏好</span>
              <el-button type="primary" size="small" @click="showPrefsModal = true">设置</el-button>
            </div>
          </template>

          <div class="preferences-list">
            <div class="preference-item">
              <span class="preference-name">感兴趣的考试类型</span>
              <div class="preference-value">
                <el-tag v-for="exam in userPreferences.examTypes" :key="exam" size="small" type="info">
                  {{ exam }}
                </el-tag>
              </div>
            </div>
            <div class="preference-item">
              <span class="preference-name">关注的知识点</span>
              <div class="preference-value">
                <el-tag v-for="knowledge in userPreferences.knowledgePoints" :key="knowledge" size="small" type="info">
                  {{ knowledge }}
                </el-tag>
              </div>
            </div>
            <div class="preference-item">
              <span class="preference-name">学习提醒时间</span>
              <span class="preference-value">{{ userPreferences.reminderTime || '未设置' }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 学习偏好设置模态框 -->
    <el-dialog v-model="showPrefsModal" title="设置学习偏好" width="600px">
      <el-form
        ref="prefsFormRef"
        v-model="editPreferences"
        class="prefs-form"
      >
        <el-form-item label="感兴趣的考试类型">
          <el-select v-model="editPreferences.examTypes" multiple placeholder="请选择">
            <el-option label="国家公务员考试" value="national_civil_service" />
            <el-option label="省级公务员考试" value="provincial_civil_service" />
            <el-option label="事业单位考试" value="institution" />
            <el-option label="教师招聘考试" value="teacher_recruitment" />
            <el-option label="选调生考试" value="selected_graduates" />
          </el-select>
        </el-form-item>

        <el-form-item label="关注的知识点">
          <el-select v-model="editPreferences.knowledgePoints" multiple placeholder="请选择">
            <el-option label="行测-言语理解" value="verbal_comprehension" />
            <el-option label="行测-数量关系" value="quantitative_relationship" />
            <el-option label="行测-判断推理" value="judgment_reasoning" />
            <el-option label="行测-资料分析" value="data_analysis" />
            <el-option label="行测-常识判断" value="common_sense" />
            <el-option label="申论-归纳概括" value="summary" />
            <el-option label="申论-综合分析" value="comprehensive_analysis" />
            <el-option label="申论-提出对策" value="countermeasures" />
            <el-option label="申论-贯彻执行" value="implementation" />
            <el-option label="申论-大作文" value="essay" />
          </el-select>
        </el-form-item>

        <el-form-item label="学习提醒时间">
          <el-time-picker
            v-model="editPreferences.reminderTime"
            placeholder="选择提醒时间"
            format="HH:mm"
            value-format="HH:mm"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPrefsModal = false">取消</el-button>
        <el-button type="primary" @click="savePreferences">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getCurrentUser, updateUserProfile } from '@/api/user';

// 编辑状态
const isEditing = ref(false);
const loading = ref(false);

// 学习偏好设置模态框
const showPrefsModal = ref(false);

// 表单引用
const profileFormRef = ref<any>();
const prefsFormRef = ref<any>();

// 性别映射
type GenderType = 'male' | 'female' | 'other';
const genderMap: Record<GenderType, string> = {
  male: '男',
  female: '女',
  other: '其他'
};

// 用户资料数据
interface UserProfileType {
  id: number;
  username: string;
  nickname: string;
  avatarUrl: string;
  level: number;
  totalScore: number;
  solvedQuestions: number;
  joinGroups: number;
  tags: string[];
  bio: string;
  gender: GenderType;
  birthday: string;
  location: string;
  phone: string;
  email: string;
  registerDate: string;
  lastLoginDate: string;
}
const userProfile = reactive<UserProfileType>({
  id: 0,
  username: '',
  nickname: '',
  avatarUrl: '',
  level: 1,
  totalScore: 0,
  solvedQuestions: 0,
  joinGroups: 0,
  tags: [],
  bio: '',
  gender: 'male',
  birthday: '',
  location: '',
  phone: '',
  email: '',
  registerDate: '',
  lastLoginDate: ''
});

// 编辑表单数据
const editForm = ref({
  nickname: '',
  gender: '',
  birthday: '',
  location: '',
  bio: '',
  phone: '',
  email: ''
});

// 表单验证规则
const profileRules = reactive({
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
      required: false
    }
  ],
  email: [
    {
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur',
      required: false
    }
  ]
});

// 用户偏好设置
const userPreferences = reactive({
  examTypes: ['national_civil_service', 'provincial_civil_service'],
  knowledgePoints: ['judgment_reasoning', 'data_analysis', 'comprehensive_analysis'],
  reminderTime: '09:00'
});

// 编辑偏好设置
interface PreferencesType {
  examTypes: string[];
  knowledgePoints: string[];
  reminderTime: string;
}
const editPreferences = ref<PreferencesType>({
  examTypes: [],
  knowledgePoints: [],
  reminderTime: ''
});

// 地区选项
const locationOptions = computed(() => {
  // 实际应用中应该从后端获取完整的地区数据
  return [
    {
      value: 'beijing',
      label: '北京市',
      children: [
        {
          value: 'haidian',
          label: '海淀区'
        },
        {
          value: 'chaoyang',
          label: '朝阳区'
        }
      ]
    },
    {
      value: 'shanghai',
      label: '上海市',
      children: [
        {
          value: 'pudong',
          label: '浦东新区'
        },
        {
          value: 'jingan',
          label: '静安区'
        }
      ]
    }
  ];
});

// 初始化编辑表单
const initEditForm = () => {
  editForm.value.nickname = userProfile.nickname;
  editForm.value.gender = userProfile.gender;
  editForm.value.birthday = userProfile.birthday;
  editForm.value.location = userProfile.location;
  editForm.value.bio = userProfile.bio;
  editForm.value.phone = userProfile.phone;
  editForm.value.email = userProfile.email;
};

// 初始化偏好设置编辑表单
const initPrefsEditForm = () => {
  editPreferences.value.examTypes = [...userPreferences.examTypes];
  editPreferences.value.knowledgePoints = [...userPreferences.knowledgePoints];
  editPreferences.value.reminderTime = userPreferences.reminderTime;
};

// 加载用户资料
const loadUserProfile = async () => {
  try {
    loading.value = true;
    console.log('开始加载用户资料...');
    
    const profile = await getCurrentUser();
    console.log('获取到的用户资料:', profile);
    
    // 更新用户资料数据
    Object.assign(userProfile, {
      id: profile.id || 0,
      username: profile.username || 'admin',
      nickname: profile.nickname || '未设置',
      avatarUrl: profile.avatar || '',
      level: 1, // 暂时设为1，后续可以从统计接口获取
      totalScore: 0, // 暂时设为0，后续可以从统计接口获取
      solvedQuestions: 0, // 暂时设为0，后续可以从统计接口获取
      joinGroups: 0, // 暂时设为0，后续可以从统计接口获取
      tags: [], // 暂时为空，后续可以从统计接口获取
      bio: profile.bio || '',
      gender: (profile.gender as GenderType) || 'male',
      birthday: profile.birthday || '',
      location: profile.location || '',
      phone: '', // 暂时为空，后续可以添加手机号字段
      email: profile.email || '',
      registerDate: profile.createdAt ? new Date(profile.createdAt).toISOString().split('T')[0] : '',
      lastLoginDate: profile.lastLogin ? new Date(profile.lastLogin).toISOString().split('T')[0] : ''
    });
    
    console.log('用户资料更新完成:', userProfile);
    
    // 初始化编辑表单
    initEditForm();
    
    ElMessage.success('用户资料加载成功');
  } catch (error) {
    console.error('加载用户资料失败', error);
    
    // 如果API失败，使用默认数据
    console.log('使用默认用户数据');
    Object.assign(userProfile, {
      id: 1,
      username: 'admin',
      nickname: '管理员',
      avatarUrl: '',
      level: 1,
      totalScore: 0,
      solvedQuestions: 0,
      joinGroups: 0,
      tags: [],
      bio: '系统管理员',
      gender: 'male' as GenderType,
      birthday: '',
      location: '',
      phone: '',
      email: 'admin@governtalk.com',
      registerDate: new Date().toISOString().split('T')[0],
      lastLoginDate: new Date().toISOString().split('T')[0]
    });
    
    initEditForm();
    ElMessage.warning('使用默认用户数据');
  } finally {
    loading.value = false;
  }
};

// 保存个人资料修改
const saveChanges = async () => {
  try {
    // 表单验证
    await profileFormRef.value.validate();
    
    // 调用API更新用户资料
    const updateData = {
      nickname: editForm.value.nickname,
      bio: editForm.value.bio,
      avatar: userProfile.avatarUrl
    };
    
    await updateUserProfile(updateData);
    
    // 更新本地数据
    Object.assign(userProfile, editForm.value);
    
    ElMessage.success('个人资料更新成功');
    isEditing.value = false;
  } catch (error) {
    console.error('更新用户资料失败', error);
    ElMessage.error('更新用户资料失败');
  }
};

// 取消编辑
const cancelEdit = () => {
  initEditForm();
  isEditing.value = false;
};

// 保存偏好设置
const savePreferences = async () => {
  try {
    // 更新偏好设置
    Object.assign(userPreferences, editPreferences.value);
    
    ElMessage.success('偏好设置保存成功');
    showPrefsModal.value = false;
  } catch (error) {
    console.error('保存偏好设置失败', error);
  }
};

// 处理头像上传
const handleAvatarUpload = () => {
  ElMessage.info('头像上传功能待实现');
};

// 组件挂载时初始化
onMounted(() => {
  loadUserProfile();
  initPrefsEditForm();
});
</script>

<style lang="scss" scoped>
.user-profile-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.profile-content {
  display: flex;
  gap: 30px;
}

.profile-sidebar {
  flex: 0 0 350px;
}

.profile-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profile-card {
  border-radius: 12px;
  overflow: hidden;
}

.avatar-section {
  text-align: center;
  padding: 30px 0;
  border-bottom: 1px solid #e5e7eb;
}

.user-avatar {
  margin: 0 auto 15px;
  border: 4px solid #f3f4f6;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-info {
  padding: 20px;
  text-align: center;
}

.user-name {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 5px 0;
}

.user-id,
.user-level {
  font-size: 14px;
  color: #6b7280;
  margin: 0 0 5px 0;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin: 15px 0;
  padding: 15px 0;
  border-top: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 20px;
  font-weight: 600;
  color: #6366f1;
  margin-bottom: 2px;
}

.stat-label {
  font-size: 12px;
  color: #6b7280;
}

.user-tags {
  padding: 0 20px 20px 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.user-bio,
.user-contact {
  padding: 20px;
  border-top: 1px solid #e5e7eb;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 10px 0;
}

.user-bio p {
  font-size: 14px;
  line-height: 1.6;
  color: #4b5563;
  margin: 0;
}

.contact-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: #4b5563;
}

.contact-item:last-child {
  margin-bottom: 0;
}

.contact-icon {
  margin-right: 10px;
  color: #6366f1;
}

.info-edit-card,
.study-stats-card,
.learning-prefs-card {
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-actions {
  display: flex;
  gap: 10px;
}

.profile-form {
  padding: 20px 0;
}

.form-value {
  color: #4b5563;
  font-size: 14px;
  line-height: 32px;
}

.stats-charts {
  padding: 20px 0;
}

.chart-item,
.learning-progress {
  margin-bottom: 30px;
}

.chart-item:last-child,
.learning-progress:last-child {
  margin-bottom: 0;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 20px 0;
}

.chart-container {
  height: 200px;
  background-color: #f9fafb;
  border-radius: 8px;
  padding: 20px;
}

.static-chart {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  height: 100%;
}

.chart-bar {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  max-width: 30px;
  margin: 0 5px;
}

.bar {
  height: 100%;
  border-radius: 4px 4px 0 0;
  margin-bottom: 5px;
  transition: all 0.3s;
}

.progress-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.progress-item {
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: #4b5563;
}

.progress-name {
  font-weight: 500;
}

.progress-percentage {
  color: #6366f1;
  font-weight: 600;
}

.preferences-list {
  padding: 20px 0;
}

.preference-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #e5e7eb;
}

.preference-item:last-child {
  border-bottom: none;
}

.preference-name {
  font-size: 14px;
  color: #4b5563;
  font-weight: 500;
}

.preference-value {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: flex-end;
  font-size: 14px;
  color: #6b7280;
}

.prefs-form {
  padding: 20px 0;
}

// 响应式设计
@media (max-width: 1024px) {
  .profile-content {
    flex-direction: column;
  }
  
  .profile-sidebar {
    flex: 1;
  }
}
</style>